package online.yangcloud.common.runner;

import online.yangcloud.common.annotation.DataTable;
import online.yangcloud.common.database.MysqlMapper;
import online.yangcloud.common.properties.DataProperty;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 初始化表结构启动器
 *
 * @author zhuboyang
 * @since 2023年09月03 15:04:57
 */
@Order(1)
@Component
public class TableInitialRunner implements ApplicationRunner {

    private static final String MYSQL_CLASS = "com.mysql.cj.jdbc.Driver";

    @Resource
    private MysqlMapper mysqlMapper;

    @Resource
    private DataProperty dataProperty;

    @Resource
    private DataSourceProperties dataSourceProperties;

    @Resource
    private ApplicationContext applicationContext;

    @Override
    public void run(ApplicationArguments args) {
        if (!dataProperty.getEnableExecuteSqlInRun()) {
            return;
        }

        // 获取所有需检测的实体类
        Map<String, Object> beans = applicationContext.getBeansWithAnnotation(DataTable.class);
        List<Object> tableClasses = new ArrayList<>(beans.size());
        beans.forEach((k, v) -> tableClasses.add(v));

        // MySQL
        if (MYSQL_CLASS.equals(dataSourceProperties.getDriverClassName())) {
            mysqlMapper.runner(tableClasses);
        }
    }

}
